package dev.entao.core.slices

import dev.entao.core.HttpAction
import dev.entao.core.HttpContext
import dev.entao.core.HttpSlice
import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotation

@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class LoginSession(val type: String )

object SessionSlice : HttpSlice {
    private const val ACC = "_ACCOUNT_ID_"
    private const val TYP = "_ACCOUNT_TYPE_"

    fun getAccountId(context: HttpContext): Int? {
        return context.getSession(ACC)?.toIntOrNull()
    }

    fun getAccountType(context: HttpContext): String? {
        return context.getSession(TYP)
    }

    fun putAccountId(context: HttpContext, accountID: Int, type: String) {
        context.putSession(ACC, accountID.toString())
        context.putSession(TYP, type)
    }

    override fun beforeRouter(context: HttpContext, cls: KClass<*>, action: HttpAction) {
        val an: LoginSession = action.findAnnotation() ?: cls.findAnnotation() ?: return
        val id = getAccountId(context) ?: return context.sendError(401)
        val type = getAccountType(context) ?: return context.sendError(401)
        if (type != an.type) {
            context.removeSession(ACC)
            context.removeSession(TYP)
            return context.sendError(401)
        }
        context.accountID = id
        context.accountType = type
    }

}